#include "VDecoderManager.h"
#include "Util/logc.h"

namespace Media{

    VDecoderManager::Ptr VDecoderManager::Instance(){
        static auto ptr = std::make_shared<VDecoderManager>();
        return ptr;
    }
    
    VDecoderManager::VDecoderManager(){
        for(DecChannel i = 0; i< MAX_DECODER_NUM; i++){
            m_decoders[i] = false;
        }
    }
    
    VDecoderManager::~VDecoderManager(){

    }

    bool VDecoderManager::CreateDecoder(VDecoder::Ptr& ptr){
        std::lock_guard<std::recursive_mutex> guard(m_mux);
        DecChannel chan;
        if(getAvailableChannel(chan)){
            ptr = std::make_shared<VDecoder>(chan);
            m_decoders[chan] = true;
            errorf("CreateDecoder success");
            return true;
        }
        
        errorf("CreateDecoder fail");
        return false;
    }
    
    bool VDecoderManager::ReleaseDecoder(const VDecoder::Ptr& ptr){
        std::lock_guard<std::recursive_mutex> guard(m_mux);
        if(ptr){
            ptr->Stop();
            DecChannel chan = ptr->GetChannel();
            if(m_decoders.find(chan) != m_decoders.end()){
                m_decoders[chan] = false;
            }
        }
        return true;
    }

    bool VDecoderManager::getAvailableChannel(DecChannel& channel){
        std::lock_guard<std::recursive_mutex> guard(m_mux);

        for(auto [key, val]: m_decoders){
            if(!val){
                channel = key;
                return true;
            }
        }
        return false;
    }
}